/**
 * 文件名: src/components/AIDialog.tsx
 * 
 * 文件概述:
 * AI对话框组件，提供用户与AI交互界面，支持聊天和内容插入到编辑器。
 * 
 * 依赖项:
 * - 'use client': 声明为客户端组件
 * - react: React核心库和hooks
 * - antd: List, Card, Input, Button, Modal, message, Spin, Tag, Checkbox, Typography组件
 * - @ant-design/icons: FileOutlined等图标组件
 * - ../utils/platform: 文件选择(showFileSelector)和AI调用(callAI)
 * - ../store: 状态管理(messages, selectedChapter, referenceFiles, editorContent, isLoading)
 * 
 * UI设计:
 * - 右侧边栏:
 *   - 宽度: 300px
 *   - 白色背景(#ffffff)
 *   - 顶部: 头像和"Writing Assistant"标题
 *   - 右上角: 设置图标和关闭按钮
 * 
 * - 对话区域:
 *   - 对话气泡样式:
 *     - 用户消息: 右对齐，浅橙色背景，白色小标签"You"
 *     - AI消息: 左对齐，浅绿色背景，含有头像，小标签"NovelAI Assistant"
 *   - 消息内容: 黑色文字，段落格式
 *   - 生成的描述文本: 引用样式，浅灰色背景
 *   
 * - 底部输入区:
 *   - 圆角输入框占据大部分宽度
 *   - 提示文字"Ask the AI for help with your writing..."
 *   - 右侧发送按钮(纸飞机图标)
 *   - "Improve Writing"按钮(左下灰色)
 *   - "Style"下拉菜单(右下灰色)
 *   - "Refresh Preview"按钮(右下黑色)
 * 
 * - 操作按钮:
 *   - "Insert"按钮: 浅绿色背景，用于插入AI响应
 *   - "Regenerate"按钮: 灰色文字，用于重新生成内容
 * 
 * 组件结构:
 * - AIDialog: () => JSX.Element
 *   - Spin: 加载状态包装器
 *     - Sider(antd)
 *       - 顶部标题栏(头像和标题)
 *       - 文件选择控制区域(Button)
 *       - FileSelector组件(条件渲染)
 *       - 已选文件标签区域(Tag组件)
 *       - 对话历史区域(List + Card)
 *       - 底部控制区:
 *         - 用户输入区域(Input.TextArea)
 *         - 功能按钮(Improve, Style, Preview)
 * 
 * - FileSelector: () => JSX.Element (内部子组件)
 *   - 文件选择列表(List + Checkbox)
 *   - 操作按钮(清除全部)
 * 
 * 状态:
 * - 本地状态:
 *   - userInput: useState("") - 用户输入内容
 *   - showFileSelector: useState(false) - 文件选择器显示状态
 * - 全局状态(从store获取):
 *   - messages: AI对话历史
 *   - selectedChapter: 当前选中章节(用于上下文)
 *   - referenceFiles: 选中的参考文件列表
 *   - isLoading.aiDialog: AI请求加载状态
 * 
 * 副作用:
 * - 消息列表更新时滚动到底部
 * - 监听快捷键(如Ctrl+Enter发送)
 * 
 * 事件处理:
 * - 参考文件选择:
 *   1. 显示/隐藏文件选择器(showFileSelector)
 *   2. 勾选/取消章节(toggleReferenceFile)
 *   3. 移除已选文件(removeReferenceFile)
 *   4. 清空所有参考(clearReferenceFiles)
 * 
 * - 发送消息: 
 *   1. 获取用户输入
 *   2. 构建上下文(buildContext): 合并当前章节和所有参考文件内容
 *   3. 调用platform.callAI(userInput, context)
 *   4. 处理响应并更新store，包含使用的参考文件信息
 *   
 * - 插入响应: 
 *   1. 调用useAppStore.getState().setEditorContent()插入AI响应
 *   2. 可选择插入模式(追加/替换)
 * 
 * 辅助函数:
 * - buildContext(): 构建发送给AI的完整上下文
 * - estimateTokens(text): 估算文本token数量
 * 
 * 消息渲染:
 * - 用户消息和AI响应使用不同样式
 * - 消息组件显示使用的参考文件名称
 * - 支持Markdown渲染(可选)
 * 
 * 错误处理:
 * - AI请求错误显示为特殊消息
 * - 文本过长时显示警告
 * - 使用message组件提示操作错误
 * 
 * 生命周期:
 * - 组件挂载: 设置事件监听器
 * - 组件卸载: 清理事件监听器，清空参考文件列表
 * 
 * 注意事项:
 * - 确保并发AI请求处理
 * - 长对话历史性能优化
 * - 文件选择器只在需要时显示
 * - 提供清晰的视觉反馈
 * - 考虑token限制
 */

'use client';

import React, { useState, useEffect, useRef, useCallback } from 'react';
import { 
  Layout,
  List, 
  Card, 
  Input, 
  Button, 
  Spin, 
  Tag, 
  Checkbox, 
  Typography,
  Avatar,
  Modal,
  Dropdown,
  Menu,
  message,
  Space,
  Tooltip,
  Divider,
  Switch,
  Form,
  Select,
  Slider
} from 'antd';
import { 
  SendOutlined, 
  FileOutlined, 
  SettingOutlined, 
  CloseOutlined,
  RobotOutlined,
  UserOutlined,
  SyncOutlined,
  PlusOutlined,
  CopyOutlined,
  DeleteOutlined,
  CaretDownOutlined,
  ThunderboltOutlined,
  CheckOutlined,
  EditOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { useAppStore } from '../store';
import { callAI, estimateTokens } from '../utils/platform';
// 引入Markdown渲染库 - 暂时注释掉，等安装后再启用
import ReactMarkdown from 'react-markdown';

const { TextArea } = Input;
const { Text, Title, Paragraph } = Typography;

// 类型定义
interface Chapter {
  id: string;
  title: string;
  content: string;
}

interface ReferenceFile {
  id: string;
  title: string;
  content: string;
  selected: boolean;
}

interface Message {
  user?: string;
  ai?: string;
  references?: string[];
}

interface FileSelectorProps {
  chapters: Chapter[];
  referenceFiles: ReferenceFile[];
  toggleReference: (id: string) => void;
  clearReferences: () => void;
}

// 设置项接口
interface AISettings {
  enableMarkdown: boolean;
  maxTokensLimit: number;
  modelName: string;
  temperature: number;
}

// 内部文件选择器组件
const FileSelector: React.FC<FileSelectorProps> = ({ 
  chapters, 
  referenceFiles, 
  toggleReference, 
  clearReferences 
}) => {
  return (
    <div className="file-selector">
      <div className="file-selector-header">
        <Text strong>选择参考文件</Text>
        <Button 
          type="text" 
          size="small" 
          onClick={clearReferences}
          disabled={!referenceFiles || referenceFiles.length === 0}
        >
          清除全部
        </Button>
      </div>
      <div className="file-selector-content">
        <List
          size="small"
          dataSource={chapters || []}
          renderItem={(chapter: Chapter) => (
            <List.Item>
              <Checkbox
                checked={referenceFiles?.some(ref => ref.id === chapter.id && ref.selected)}
                onChange={() => toggleReference(chapter.id)}
              >
                <Space>
                  <FileOutlined />
                  <Text ellipsis>{chapter.title}</Text>
                </Space>
              </Checkbox>
            </List.Item>
          )}
          locale={{ emptyText: '没有可用的章节' }}
        />
      </div>
    </div>
  );
};

// AI对话组件
const AIDialog = () => {
  // 本地状态
  const [userInput, setUserInput] = useState('');
  const [showFileSelector, setShowFileSelector] = useState(false);
  const [insertMode, setInsertMode] = useState('append'); // 'append' 或 'replace'
  const messagesEndRef = useRef<HTMLDivElement>(null);
  // 新增状态
  const [showSettings, setShowSettings] = useState(false);
  const [showPreview, setShowPreview] = useState(false);
  const [previewContent, setPreviewContent] = useState('');
  const [aiSettings, setAISettings] = useState<AISettings>({
    enableMarkdown: true,
    maxTokensLimit: 4000,
    modelName: 'gpt-3.5-turbo',
    temperature: 0.7
  });
  
  // 全局状态
  const { 
    messages, 
    chapters,
    selectedChapter, 
    referenceFiles, 
    addMessage,
    toggleReferenceFile,
    removeReferenceFile,
    clearReferenceFiles,
    setEditorContent,
    editorContent,
    isLoading,
    callAI: storeCallAI
  } = useAppStore();
  
  // 滚动到最新消息
  useEffect(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages]);
  
  // 监听快捷键
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // 检测 Ctrl+Enter 快捷键
      if (e.ctrlKey && e.key === 'Enter') {
        handleSendMessage();
      }
    };
    
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [userInput]);
  
  // 组件卸载时清理
  useEffect(() => {
    return () => {
      // 可选：组件卸载时清空参考文件列表
      // clearReferenceFiles();
    };
  }, []);
  
  // 构建发送给AI的上下文
  const buildContext = useCallback(() => {
    let context = '';
    
    // 添加当前章节内容
    if (selectedChapter) {
      context += `当前章节 "${selectedChapter.title}":\n${selectedChapter.content}\n\n`;
    }
    
    // 添加参考文件内容
    const selectedReferences = referenceFiles?.filter(ref => ref.selected) || [];
    if (selectedReferences.length > 0) {
      context += '参考文件:\n';
      selectedReferences.forEach(ref => {
        context += `--- ${ref.title} ---\n${ref.content}\n\n`;
      });
    }
    
    return context;
  }, [selectedChapter, referenceFiles]);
  
  // 处理设置变更
  const handleSettingsChange = (newSettings: Partial<AISettings>) => {
    setAISettings({
      ...aiSettings,
      ...newSettings
    });
  };
  
  // 设置弹窗组件
  const SettingsModal = () => (
    <Modal
      title="AI助手设置"
      open={showSettings}
      onCancel={() => setShowSettings(false)}
      onOk={() => setShowSettings(false)}
      width={500}
    >
      <Form layout="vertical">
        <Form.Item label="启用Markdown渲染">
          <Switch 
            checked={aiSettings.enableMarkdown} 
            onChange={(checked) => handleSettingsChange({ enableMarkdown: checked })}
          />
        </Form.Item>
        <Form.Item label="最大Token限制">
          <Input 
            type="number" 
            value={aiSettings.maxTokensLimit}
            onChange={(e) => handleSettingsChange({ maxTokensLimit: Number(e.target.value) })}
          />
        </Form.Item>
        <Form.Item label="AI模型">
          <Select 
            value={aiSettings.modelName}
            onChange={(value) => handleSettingsChange({ modelName: value })}
            options={[
              { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo' },
              { value: 'gpt-4', label: 'GPT-4' },
            ]}
          />
        </Form.Item>
        <Form.Item label="温度 (创造性 0-1)">
          <Slider 
            min={0} 
            max={1} 
            step={0.1} 
            value={aiSettings.temperature}
            onChange={(value) => handleSettingsChange({ temperature: value })}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
  
  // 预览弹窗组件
  const PreviewModal = () => (
    <Modal
      title="生成内容预览"
      open={showPreview}
      onCancel={() => setShowPreview(false)}
      footer={[
        <Button key="close" onClick={() => setShowPreview(false)}>
          关闭
        </Button>,
        <Button 
          key="insert" 
          type="primary" 
          onClick={() => {
            handleInsertToEditor(previewContent);
            setShowPreview(false);
          }}
        >
          插入到编辑器
        </Button>
      ]}
      width={700}
    >
      <div className="preview-content">
        {aiSettings.enableMarkdown ? (
          <ReactMarkdown>{previewContent}</ReactMarkdown>
        ) : (
          <div style={{ whiteSpace: 'pre-wrap' }}>{previewContent}</div>
        )}
      </div>
    </Modal>
  );
  
  // 处理预览功能
  const handlePreview = () => {
    // 获取最新的AI响应
    let lastAIResponse = '';
    for (let i = messages.length - 1; i >= 0; i--) {
      if (messages[i].ai) {
        lastAIResponse = messages[i].ai;
        break;
      }
    }
    
    if (!lastAIResponse) {
      message.warning('没有找到可预览的AI回复');
      return;
    }
    
    setPreviewContent(lastAIResponse);
    setShowPreview(true);
  };
  
  // 关闭对话框
  const handleCloseDialog = () => {
    // 触发自定义事件通知父组件
    const event = new CustomEvent('toggle-ai-dialog', {
      detail: { visible: false }
    });
    window.dispatchEvent(event);
    
    // 可选：清空当前状态
    setUserInput('');
  };
  
  // 渲染消息内容(支持Markdown)
  const renderMessageContent = (content?: string) => {
    if (!content) return null;
    
    if (aiSettings.enableMarkdown) {
      return (
        <div className="markdown-content">
          <ReactMarkdown>{content}</ReactMarkdown>
        </div>
      );
    }
    
    return <Paragraph>{content}</Paragraph>;
  };
  
  // 发送消息给AI
  const handleSendMessage = async () => {
    if (!userInput.trim()) {
      message.warning('请输入问题');
      return;
    }
    
    const prompt = userInput.trim();
    setUserInput('');
    
    // 构建上下文
    const context = buildContext();
    
    // 估算token数量，避免超出限制
    const totalTokens = estimateTokens(prompt) + estimateTokens(context);
    if (totalTokens > aiSettings.maxTokensLimit) {
      message.warning(`提示和上下文内容过长，超出了${aiSettings.maxTokensLimit}token限制，请减少选择的参考文件或缩短提示`);
      return;
    }
    
    // 使用store的callAI方法，它会自动处理loading状态和消息添加
    try {
      await storeCallAI(prompt);
    } catch (error: any) {
      message.error(`AI请求失败: ${error.message || '未知错误'}`);
    }
  };
  
  // 插入AI响应到编辑器
  const handleInsertToEditor = (content: string) => {
    if (!content) return;
    
    // 根据当前的insertMode决定如何插入内容
    if (insertMode === 'replace') {
      // 通过自定义事件通知Editor组件替换选中内容
      const event = new CustomEvent('ai-response', {
        detail: {
          type: 'ai-response',
          content,
          mode: 'replace'
        }
      });
      window.dispatchEvent(event);
    } else {
      // 追加模式：通过自定义事件通知Editor组件插入内容
      const event = new CustomEvent('ai-response', {
        detail: {
          type: 'ai-response',
          content,
          mode: 'append'
        }
      });
      window.dispatchEvent(event);
    }
    
    message.success('内容已插入到编辑器');
  };
  
  // 重新生成AI响应
  const handleRegenerate = async () => {
    if (messages.length === 0) return;
    
    // 获取最后一条用户消息
    let lastUserPrompt = '';
    for (let i = messages.length - 1; i >= 0; i--) {
      if (messages[i].user) {
        lastUserPrompt = messages[i].user;
        break;
      }
    }
    
    if (!lastUserPrompt) {
      message.warning('未找到可重新生成的提示');
      return;
    }
    
    // 使用上一次的提示重新请求AI
    try {
      await storeCallAI(lastUserPrompt);
    } catch (error: any) {
      message.error(`重新生成失败: ${error.message || '未知错误'}`);
    }
  };
  
  // 改进文本功能（检测选中的文本进行优化）
  const handleImproveText = () => {
    // 触发自定义事件获取编辑器选中内容
    const event = new CustomEvent('get-selection', {
      detail: { callback: (selectedText: string) => {
        if (!selectedText) {
          message.warning('请先在编辑器中选择文本');
          return;
        }
        
        // 设置提示并自动发送
        const improvePrompt = `请帮我改进以下文本，使其更加流畅生动:\n\n${selectedText}`;
        setUserInput(improvePrompt);
        setTimeout(() => {
          handleSendMessage();
        }, 100);
      }}
    });
    window.dispatchEvent(event);
  };
  
  // 风格选择菜单
  const styleMenu = (
    <Menu 
      onClick={({key}) => {
        // 设置提示并自动发送
        let stylePrompt = '';
        
        switch(key) {
          case 'elegant':
            stylePrompt = '请将我的文章改写成优雅的风格，保持原意';
            break;
          case 'concise':
            stylePrompt = '请将我的文章改写成简洁的风格，保持原意';
            break;
          case 'vivid':
            stylePrompt = '请将我的文章改写成生动的风格，增加细节描写';
            break;
          case 'academic':
            stylePrompt = '请将我的文章改写成学术的风格，使用专业术语';
            break;
          default:
            return;
        }
        
        // 触发自定义事件获取编辑器选中内容
        const event = new CustomEvent('get-selection', {
          detail: { callback: (selectedText: string) => {
            if (!selectedText) {
              message.warning('请先在编辑器中选择文本');
              return;
            }
            
            // 设置提示并自动发送
            const fullPrompt = `${stylePrompt}:\n\n${selectedText}`;
            setUserInput(fullPrompt);
            setTimeout(() => {
              handleSendMessage();
            }, 100);
          }}
        });
        window.dispatchEvent(event);
      }}
    >
      <Menu.Item key="elegant">优雅风格</Menu.Item>
      <Menu.Item key="concise">简洁风格</Menu.Item>
      <Menu.Item key="vivid">生动风格</Menu.Item>
      <Menu.Item key="academic">学术风格</Menu.Item>
    </Menu>
  );
  
  // 渲染参考文件标签
  const renderReferenceTags = () => {
    const selectedRefs = referenceFiles?.filter(ref => ref.selected) || [];
    
    if (selectedRefs.length === 0) return null;
    
    return (
      <div className="reference-tags">
        <Text type="secondary" style={{ fontSize: 12 }}>已选参考文件:</Text>
        <div className="tags-container">
          {selectedRefs.map(ref => (
            <Tag 
              key={ref.id}
              closable
              onClose={() => removeReferenceFile(ref.id)}
            >
              {ref.title}
            </Tag>
          ))}
        </div>
      </div>
    );
  };
  
  return (
    <Spin spinning={!!isLoading?.ai} tip="AI思考中...">
      <div className="ai-dialog-container">
        {/* 顶部标题栏 */}
        <div className="ai-dialog-header">
          <div className="header-left">
            <Avatar icon={<RobotOutlined />} />
            <Title level={5} style={{ margin: 0 }}>Writing Assistant</Title>
          </div>
          <div className="header-right">
            <Button 
              type="text" 
              icon={<SettingOutlined />} 
              onClick={() => setShowSettings(true)}
            />
            <Button 
              type="text" 
              icon={<CloseOutlined />} 
              onClick={handleCloseDialog}
            />
          </div>
        </div>
        
        {/* 文件选择 */}
        <div className="file-control">
          <Button 
            type="text" 
            icon={<FileOutlined />}
            onClick={() => setShowFileSelector(!showFileSelector)}
          >
            {showFileSelector ? '隐藏文件选择' : '选择参考文件'}
          </Button>
        </div>
        
        {/* 文件选择器 */}
        {showFileSelector && (
          <FileSelector 
            chapters={chapters || []}
            referenceFiles={referenceFiles || []}
            toggleReference={toggleReferenceFile}
            clearReferences={clearReferenceFiles}
          />
        )}
        
        {/* 已选参考文件标签 */}
        {renderReferenceTags()}
        
        {/* 对话历史区域 */}
        <div className="messages-container">
          {messages.length === 0 ? (
            <div className="empty-messages">
              <Text type="secondary">尚无对话历史，开始与AI助手交流吧</Text>
            </div>
          ) : (
            <List
              itemLayout="vertical"
              dataSource={messages}
              renderItem={(message: Message) => (
                <List.Item>
                  {message.user ? (
                    <div className="user-message">
                      <div className="message-content">
                        <Tag color="blue">You</Tag>
                        <Paragraph>{message.user}</Paragraph>
                      </div>
                    </div>
                  ) : (
                    <div className="ai-message">
                      <div className="message-content">
                        <div className="message-header">
                          <Avatar size="small" icon={<RobotOutlined />} />
                          <Tag color="green">AI</Tag>
                        </div>
                        
                        {/* 使用Markdown渲染 */}
                        {renderMessageContent(message.ai)}
                        
                        {/* 消息引用的参考文件 */}
                        {message.references && message.references.length > 0 && (
                          <div className="references">
                            <Text type="secondary" style={{ fontSize: 12 }}>参考文件:</Text>
                            {message.references.map(refId => {
                              const ref = chapters?.find(chapter => chapter.id === refId);
                              return ref ? (
                                <Tag key={refId} color="cyan" style={{ margin: '0 4px' }}>
                                  {ref.title}
                                </Tag>
                              ) : null;
                            })}
                          </div>
                        )}
                        
                        {/* 操作按钮 */}
                        <div className="message-actions">
                          <Tooltip title="插入到编辑器">
                            <Button 
                              type="primary" 
                              size="small"
                              onClick={() => handleInsertToEditor(message.ai || '')}
                            >
                              插入
                            </Button>
                          </Tooltip>
                          <Dropdown 
                            overlay={(
                              <Menu>
                                <Menu.Item key="append" onClick={() => setInsertMode('append')}>
                                  追加 {insertMode === 'append' && <CheckOutlined />}
                                </Menu.Item>
                                <Menu.Item key="replace" onClick={() => setInsertMode('replace')}>
                                  替换选中 {insertMode === 'replace' && <CheckOutlined />}
                                </Menu.Item>
                              </Menu>
                            )}
                            trigger={['click']}
                          >
                            <Button type="text" size="small">
                              <CaretDownOutlined />
                            </Button>
                          </Dropdown>
                          <Button 
                            type="text" 
                            size="small"
                            onClick={handleRegenerate}
                          >
                            重新生成
                          </Button>
                        </div>
                      </div>
                    </div>
                  )}
                </List.Item>
              )}
            />
          )}
          <div ref={messagesEndRef} />
        </div>
        
        {/* 底部控制区 */}
        <div className="input-container">
          <TextArea
            value={userInput}
            onChange={e => setUserInput(e.target.value)}
            placeholder="询问AI，寻求写作帮助..."
            autoSize={{ minRows: 2, maxRows: 6 }}
            onPressEnter={e => {
              if (e.ctrlKey) {
                handleSendMessage();
                e.preventDefault();
              }
            }}
          />
          
          <div className="input-actions">
            <Button 
              type="primary" 
              shape="circle" 
              icon={<SendOutlined />} 
              onClick={handleSendMessage}
            />
          </div>
          
          <div className="function-buttons">
            <Button 
              type="default"
              icon={<EditOutlined />}
              onClick={handleImproveText}
            >
              改进文本
            </Button>
            <Dropdown overlay={styleMenu} trigger={['click']}>
              <Button>
                风格 <CaretDownOutlined />
              </Button>
            </Dropdown>
            <Button 
              type="primary"
              icon={<EyeOutlined />}
              onClick={handlePreview}
            >
              预览
            </Button>
          </div>
        </div>
      </div>
      
      {/* 设置弹窗 */}
      <SettingsModal />
      
      {/* 预览弹窗 */}
      <PreviewModal />
      
      <style jsx global>{`
        .ai-dialog-container {
          display: flex;
          flex-direction: column;
          height: 100%;
          background-color: white;
          padding: 0;
        }
        
        .ai-dialog-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 16px;
          border-bottom: 1px solid var(--border-color);
        }
        
        .header-left {
          display: flex;
          align-items: center;
          gap: 12px;
        }
        
        .header-right {
          display: flex;
          gap: 8px;
        }
        
        .file-control {
          padding: 8px 16px;
          border-bottom: 1px solid var(--border-color);
        }
        
        .file-selector {
          padding: 8px 16px;
          border-bottom: 1px solid var(--border-color);
          max-height: 200px;
          overflow-y: auto;
        }
        
        .file-selector-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
        }
        
        .reference-tags {
          padding: 8px 16px;
          border-bottom: 1px solid var(--border-color);
        }
        
        .tags-container {
          margin-top: 8px;
          display: flex;
          flex-wrap: wrap;
          gap: 4px;
        }
        
        .messages-container {
          flex: 1;
          overflow-y: auto;
          padding: 16px;
          background-color: #f9f9f9;
        }
        
        .empty-messages {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 100%;
        }
        
        .user-message {
          display: flex;
          justify-content: flex-end;
          margin-bottom: 16px;
        }
        
        .ai-message {
          display: flex;
          justify-content: flex-start;
          margin-bottom: 16px;
        }
        
        .message-content {
          padding: 12px;
          border-radius: 8px;
          max-width: 85%;
        }
        
        .user-message .message-content {
          background-color: #f0f7ff;
        }
        
        .ai-message .message-content {
          background-color: #f0fff7;
        }
        
        .message-header {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;
        }
        
        .references {
          margin-top: 8px;
          font-size: 12px;
        }
        
        .message-actions {
          display: flex;
          gap: 8px;
          margin-top: 8px;
          justify-content: flex-end;
        }
        
        .input-container {
          padding: 16px;
          border-top: 1px solid var(--border-color);
        }
        
        .input-actions {
          display: flex;
          justify-content: flex-end;
          margin-top: 8px;
        }
        
        .function-buttons {
          display: flex;
          justify-content: space-between;
          margin-top: 16px;
        }
        
        .markdown-content {
          font-size: 14px;
          line-height: 1.6;
        }
        
        .markdown-content h1,
        .markdown-content h2,
        .markdown-content h3 {
          margin-top: 16px;
          margin-bottom: 8px;
        }
        
        .markdown-content pre {
          background-color: #f1f1f1;
          padding: 8px;
          border-radius: 4px;
          overflow-x: auto;
        }
        
        .markdown-content code {
          background-color: #f1f1f1;
          padding: 2px 4px;
          border-radius: 4px;
        }
        
        .markdown-content blockquote {
          border-left: 4px solid #ccc;
          margin-left: 0;
          padding-left: 16px;
          color: #666;
        }
        
        .preview-content {
          max-height: 500px;
          overflow-y: auto;
          padding: 16px;
          border: 1px solid #eee;
          border-radius: 4px;
        }
      `}</style>
    </Spin>
  );
};

export default AIDialog;